<?php
declare(strict_types=1);

namespace app\common\job;

use app\common\enums\QuestionTypeEnum;
use app\common\model\banxi\learn\LearnReadingArticleAnswer;
use app\common\model\banxi\learn\LearnReadingArticleExtend;
use app\common\service\DouBaoAiArticleQuestionService;
use think\facade\Log;
use think\queue\Job;

/*
 * ai文章题目
 * */
class AiArticleQuestionRunner
{
    public function fire(Job $job, array $data): void
    {

        logSave([
            'file' => __FILE__,
            'message' => 'AiArticleQuestionRunner Exec',
            'data' => $data,
            'start_time' => date('Y-m-d H:i:s')
        ], 'AiArticleQuestionRunner');
        $readingArticleId = $data['readingArticleId'];
        $studentId = $data['studentId'];
        $trainerId = $data['trainerId'];
        $articleContent = $data['articleContent'];
        $readingArticleExtendId = $data['readingArticleExtendId'];
        try {
            // 调用AI服务生成题目
            $DouBaoAiArticleQuestionService = new DouBaoAiArticleQuestionService();
            $result = $DouBaoAiArticleQuestionService->getArticleQuestionByContent($articleContent);
//            $result =
//            [
//                [
//                    'questionName' => 'How did Lucy feel when she replied to the narrator’s invitation?',
//                    'answer' => 'A',
//                    'option' =>
//                        [
//                            [
//                            'value' => 'A',
//                            'name' => 'Joyful'
//                            ],
//                            [
//                            'value' => 'B',
//                            'name' => 'Tired'
//                            ],
//                            [
//                            'value' => 'C',
//                            'name' => 'Sad'
//                            ],
//                            [
//                            'value' => 'D',
//                            'name' => 'Indifferent'
//                            ]
//                        ],
//                    'analysis' => '文章第二段明确提到"Lucy’s reply came quickly, full of joy"（Lucy的回答很快，充满喜悦）。"Joyful"（快乐的、喜悦的）与"full of joy"含义一致，因此选项A正确。'
//                ],
//                [
//                    'questionName' => 'How did Lucy feel when she replied to the narrator’s invitation?',
//                    'answer' => 'A',
//                    'option' =>
//                        [
//                            [
//                                'value' => 'A',
//                                'name' => 'Joyful'
//                            ],
//                            [
//                                'value' => 'B',
//                                'name' => 'Tired'
//                            ],
//                            [
//                                'value' => 'C',
//                                'name' => 'Sad'
//                            ],
//                            [
//                                'value' => 'D',
//                                'name' => 'Indifferent'
//                            ]
//                        ],
//                    'analysis' => '文章第二段明确提到"Lucy’s reply came quickly, full of joy"（Lucy的回答很快，充满喜悦）。"Joyful"（快乐的、喜悦的）与"full of joy"含义一致，因此选项A正确。'
//                ],
//                [
//                    'questionName' => 'How did Lucy feel when she replied to the narrator’s invitation?',
//                    'answer' => 'A',
//                    'option' =>
//                        [
//                            [
//                                'value' => 'A',
//                                'name' => 'Joyful'
//                            ],
//                            [
//                                'value' => 'B',
//                                'name' => 'Tired'
//                            ],
//                            [
//                                'value' => 'C',
//                                'name' => 'Sad'
//                            ],
//                            [
//                                'value' => 'D',
//                                'name' => 'Indifferent'
//                            ]
//                        ],
//                    'analysis' => '文章第二段明确提到"Lucy’s reply came quickly, full of joy"（Lucy的回答很快，充满喜悦）。"Joyful"（快乐的、喜悦的）与"full of joy"含义一致，因此选项A正确。'
//                ]
//            ];
//            halt($result);
            // 保存题目信息
            if ($result) {
                // 保存题目信息
                $answerList = [];
                foreach ($result as $question) {
                    $answerList[] = [
                        'readingArticleId' => $readingArticleId,
                        'studentId' => $studentId,
                        'trainerId' => $trainerId,
                        'questionName' => $question['questionName'],
                        'questionType' => QuestionTypeEnum::E1, // 默认单选题
                        'option' => json_encode($question['option'], JSON_UNESCAPED_UNICODE),
                        'answer' => json_encode(explode(',',$question['answer']), JSON_UNESCAPED_UNICODE),
                        'analysis' => $question['analysis'],
                        'createTime' => time(),
                        'updateTime' => time()
                    ];

                }
                logSave($answerList, 'ai文章题目');
                // 批量保存题目
                $readingArticleAnswerModel = new LearnReadingArticleAnswer();
                $readingArticleAnswerModel->saveAll($answerList);

                // 更新状态为成功
                $LearnReadingArticleExtendModel = new LearnReadingArticleExtend();
                $LearnReadingArticleExtendModel->update([
                    'aiQuestionStatus' => '2'
                ], ['id' => $readingArticleExtendId]);



            } else {
                // 任务执行失败，处理失败情况
//                $this->handleFailure($job, $data);
            }
            // 任务执行成功，删除任务
            $job->delete();
        } catch (\Exception $e) {
            // 捕获异常并处理失败情况
//            $this->handleFailure($job, $data);
            logSave([
                'file' => __FILE__,
                'message' => "AiArticleQuestionRunner Exception",
                'data' => $data,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 'AiArticleQuestionRunner');
        } catch (\Throwable $t) {
            // 捕获致命错误
//            $this->handleFailure($job, $data);
            logSave([
                'file' => __FILE__,
                'message' => "AiArticleQuestionRunner Throwable",
                'data' => $data,
                'error' => $t->getMessage(),
                'trace' => $t->getTraceAsString()
            ], 'AiArticleQuestionRunner');
        } catch (\PDOException $P) {
            // 捕获致命错误
//            $this->handleFailure($job, $data);
            logSave([
                'file' => __FILE__,
                'message' => "AiArticleQuestionRunner Throwable",
                'data' => $data,
                'error' => $P->getMessage(),
                'trace' => $P->getTraceAsString()
            ], 'AiArticleQuestionRunner');
        }
    }

    /**
     * 处理任务失败情况
     */
    private function handleFailure(Job $job, array $data): void
    {
        $attempts = $job->attempts();

        // 如果重试次数超过3次，则删除任务并记录失败
        if ($attempts > 3) {
            $job->delete();
            logSave([
                'file' => __FILE__,
                'message' => "队列任务失败超过3次，已删除",
                'data' => $data,
                'attempts' => $attempts,
                'end_time' => date('Y-m-d H:i:s')
            ], 'AiArticleQuestionRunner');
        } else {
            logSave([
                'file' => __FILE__,
                'message' => "队列任务失败，将自动重试",
                'data' => $data,
                'attempts' => $attempts,
            ], 'AiArticleQuestionRunner');
            // 任务会自动重新加入队列
        }
    }

    /**
     * 默认任务处理
     */
    private function processDefault(array $data): bool
    {
        // 实现默认处理逻辑
        return true;
    }

    /**
     * 任务失败回调
     */
    public function failed(array $data): void
    {
        // 记录失败任务日志
        Log::error('队列任务最终失败', $data);
    }
}
